// 格式化更新时间
function formatUpdateTime(timeValue) {
    const date = new Date(timeValue);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}更新`;
}

// 跳转到图书详情页
function goToBookDetail(bookId) {
    window.location.href = `./jinwen-bookDetail.html?id=${bookId}`;
}

// 全局变量存储当前分类和排序状态
let currentCategory = 21; // 默认分类ID
let currentSort = 5; // 默认排序方式为更新时间(5)

// 分类与对应ID映射
const categoryMap = {
    '总共': 21,
    '全部':0,
    '古代言情': 157,
    '历史传奇':161,
    '异世架空':162,
    '宫廷世家':163,
    '布衣工商':164,
    '玄幻奇幻':165,
    '仙侠武侠':166,
    '现代言情': 158,
    '古代非言情':159,
    '现代非言情':160,
    '短篇小说':560
};

// 各分类下不同排序的书籍总数映射
const categorySortCountMap = {
    0: {5:40, 4:35, 6: 40, 3: 6, 1: 6, 2: 6},
    21: {5: 490, 4: 487, 6: 490, 3: 463, 1: 463, 2: 463},
    157: {5: 253, 4: 250, 6: 253, 3: 233, 1: 233, 2: 233},
    158: {5: 219, 4: 219, 6: 219, 3: 212, 1: 212, 2: 212},
    159: {5: 7, 4: 7, 6: 7, 3: 7, 1: 7, 2: 7},
    160: {5:11, 4: 11, 6: 11, 3: 11, 1: 11, 2: 11},
    560: {5:0, 4: 0, 6: 0, 3: 0, 1: 0, 2: 0},
    161: {5:161, 4:160, 6: 161, 3: 160, 1: 160, 2: 160},
    162: {5:30, 4:29, 6: 30, 3: 18, 1: 18, 2: 18},
    163: {5:26, 4:26, 6: 26, 3: 23, 1: 23, 2: 23},
    164: {5:17, 4:17, 6: 17, 3: 14, 1: 14, 2: 14},
    165: {5:13, 4:13, 6: 13, 3: 13, 1: 13, 2: 13},
    166: {5: 6, 4: 5, 6: 6, 3: 5, 1: 5, 2: 5},
};

// 切换内容显示状态
function toggleContentDisplay(hasData) {
    const tabContent = document.querySelector('.tab-content');
    const laypage = document.getElementById('demo-laypage-all');
    const elseContent = document.querySelector('.else-content');
    
    // 确保元素存在再操作
    if (tabContent) tabContent.style.display = hasData ? 'flex' : 'none';
    if (laypage) laypage.style.display = hasData ? 'flex' : 'none';
    if (elseContent) elseContent.style.display = hasData ? 'none' : 'flex';
}

function fetchBooks(pageNo, sort = currentSort, category = currentCategory){
    // 更新总数显示
    const totalCount = categorySortCountMap[category]?.[sort] || 0;
    document.getElementById('totalCount').textContent = totalCount;
    
    fetch(`https://app2.motie.com/pc/books/search?pageNo=${pageNo}&pageSize=20&categoryId=${category}&sort=${sort}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ pageNo, pageSize: 20, categoryId: category, sort })
    })
    .then(res => res.ok ? res.json() : Promise.reject(res.status))
    .then(({ data }) => {
        // 检查是否有数据
        const hasData = data?.items && data.items.length > 0;
        
        // 根据是否有数据切换显示状态
        toggleContentDisplay(hasData);
        
        if (!hasData) return;
      
        const content = document.querySelector('.tab-content');
        if (!content) throw "未找到容器元素";
        
        // 按对应参数进行排序处理
        let books = data.items;
        if (sort === 4) {
            // 推荐票排序：按推荐票数量降序
            books = [...books].sort((a, b) => (b.recommendCount || 0) - (a.recommendCount || 0));
        } else if (sort === 6) {
            // 字数排序：按字数降序
            books = [...books].sort((a, b) => (b.words || 0) - (a.words || 0));
        } else if ([1, 2, 3].includes(sort)) {
            // 人气排序：按人气值降序
            books = [...books].sort((a, b) => (b.popularity || 0) - (a.popularity || 0));
        }
        
        content.innerHTML = books.map(book => `
            <div class="box">
                <img src="${book.bookIconUrl}" data-bookid="${book.bookId}" 
                     onclick="goToBookDetail(${book.bookId})">
                <div class="rightbox">
                    <p class="bookname" data-bookid="${book.bookId}" 
                       onclick="goToBookDetail(${book.bookId})">${book.bookName}</p>
                    <p>${book.authorName}&nbsp;|&nbsp;${book.categoryVO ? (book.categoryVO.name ? book.categoryVO.name : '') : ''}&nbsp;|&nbsp;${book.finish ? '已完结' : '连载中'}</p>
                    <p class="info">${book.introduction}</p>
                    <p>
                        <span>${book.words}字 | </span>
                        <span class="red">${formatUpdateTime(book.lastChapterTime)}</span>
                    </p>
                </div>
            </div>     
        `).join('');
    })
    .catch(err => {
        console.error("请求失败:", err);
        // 请求失败时也显示空状态
        toggleContentDisplay(false);
    });
}

// 初始化页面并加载第一页数据
layui.use(['laypage'], function() {
    const laypage = layui.laypage;
    let currentPage = 1;
    const firstnameElement = document.querySelector('.firstname');
    
    // 初始化时设置总人气不高亮
    firstnameElement.textContent = '总人气';
    firstnameElement.style.color = '#333'; // 设置默认颜色（不高亮）
    // 初始化时总人气选项不添加选中样式
    const totalPopularityItem = document.querySelector('.tipshover p[data-sort="3"]');
    if (totalPopularityItem) {
        totalPopularityItem.classList.remove('on');
    }
    // 设置更新时间排序按钮为选中状态
    const updateTimeBtn = document.querySelector('.tab-item-btn a[data-sort="5"]');
    if (updateTimeBtn) {
        updateTimeBtn.classList.add('on');
    }
    
    // 渲染分页
    const renderPage = () => {
        const totalCount = categorySortCountMap[currentCategory]?.[currentSort] || 0;
        
        // 先根据总数判断是否显示空状态
        toggleContentDisplay(totalCount > 0);
        
        laypage.render({
            elem: 'demo-laypage-all',
            count: totalCount,
            limit: 20,
            limits: [20],
            layout: ['count', 'prev', 'page', 'next', 'skip'],
            jump: function(obj, first) {
                if(!first){
                    currentPage = obj.curr;
                    fetchBooks(currentPage);
                } else if (first && currentPage === 1) {
                    // 首次加载第一页
                    fetchBooks(1);
                }
            }
        });
    };
    
    // 初始渲染分页
    renderPage();
    
    // 排序切换事件
    document.querySelectorAll('.tab-item-btn a').forEach(btn => {
        btn.addEventListener('click', function() {
            // 更新活跃状态
            document.querySelectorAll('.tab-item-btn a').forEach(el => el.classList.remove('on'));
            this.classList.add('on');
            
            // 重置人气按钮的颜色为默认#333
            firstnameElement.style.color = '#333';
            // 重置人气选项选中状态
            document.querySelectorAll('.tipshover p').forEach(el => el.classList.remove('on'));
            
            // 获取排序类型
            currentSort = parseInt(this.dataset.sort);
            currentPage = 1;
            
            // 重新渲染分页和数据
            renderPage();
        });
    });

    // 人气排序切换功能
    document.querySelectorAll('.tipshover p').forEach(item => {
        item.addEventListener('click', function() {
            // 更新活跃状态
            document.querySelectorAll('.tipshover p').forEach(el => el.classList.remove('on'));
            this.classList.add('on'); // 只有选中时才添加高亮样式
            
            // 获取对应的排序类型和文本
            const sortText = this.textContent.trim();
            const sortMap = {
                '总人气': 3,
                '周人气': 1,
                '月人气': 2
            };
            currentSort = sortMap[sortText];
            
            // 更新显示文本和颜色（只有选中时才高亮）
            firstnameElement.textContent = sortText;
            firstnameElement.style.color = '#0fb295';
            
            // 重置其他排序按钮状态
            document.querySelectorAll('.tab-item-btn a').forEach(el => el.classList.remove('on'));
            
            // 更新总数显示并重新加载数据
            currentPage = 1;
            renderPage();
            
            // 隐藏提示框
            document.querySelector('.tipshover').style.display = 'none';
        });
    });

    // 分类点击事件
    document.querySelectorAll('.selectTag a').forEach(link => {
        const categoryName = link.textContent.trim();
        const categoryId = categoryMap[categoryName];
        
        if (categoryId !== undefined) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                // 更新当前分类
                currentCategory = categoryId;
                currentPage = 1;
                // 重置排序为更新时间
                currentSort = 5;
                // 重置排序按钮状态
                document.querySelectorAll('.tab-item-btn a').forEach(el => el.classList.remove('on'));
                if (updateTimeBtn) {
                    updateTimeBtn.classList.add('on');
                }
                // 更新人气标签显示为不高亮
                firstnameElement.textContent = '总人气';
                firstnameElement.style.color = '#333';
                // 确保总人气选项不高亮
                document.querySelectorAll('.tipshover p').forEach(el => el.classList.remove('on'));
                
                // 重新渲染分页和数据
                renderPage();
            });
        }
    });
});

// 人气下拉框显示控制
const trigger = document.querySelector('.firstname');
const tips = document.querySelector('.tipshover');
trigger.onclick = () => {
    tips.style.display = tips.style.display === 'block' ? 'none' : 'block';
};
document.onclick = e => {
    if (!trigger.contains(e.target) && !tips.contains(e.target)) {
        tips.style.display = 'none';
    }
};

// 分类标签样式控制
document.querySelectorAll('.selectTag').forEach(tag => {
    // 默认只为包含"全部"文字的.selectTag添加curr类
    const tagText = tag.querySelector('a').textContent.trim();
    if (tagText === '全部') {
        tag.classList.add('curr');
        // 默认显示"全部"对应的二级菜单（如果存在）
        const secondType = tag.querySelector('.second-type');
        if (secondType) {
            secondType.style.display = 'block';
        }
    }
    
    tag.addEventListener('click', function(e) {
        // 阻止事件冒泡，避免触发父元素事件
        e.stopPropagation();
        
        // 获取同组的所有.selectTag（同一selectlist内的）
        const parentList = this.closest('.selectlist');
        if (parentList) {
            // 移除同组所有.selectTag的curr类
            parentList.querySelectorAll('.selectTag').forEach(sibling => {
                sibling.classList.remove('curr');
                // 隐藏其他标签的下拉框
                const siblingSecondType = sibling.querySelector('.second-type');
                if (siblingSecondType) {
                    siblingSecondType.style.display = 'none';
                }
            });
            
            // 为当前点击的标签添加curr类
            this.classList.add('curr');
            
            // 显示当前标签的下拉框（如果存在）
            const secondType = this.querySelector('.second-type');
            if (secondType) {
                secondType.style.display = 'block';
            }
        }
    });
});

// 点击页面其他区域时，只关闭下拉框，保留curr类
document.addEventListener('click', function() {
    document.querySelectorAll('.selectTag').forEach(tag => {
        // 隐藏所有二级菜单
        const secondType = tag.querySelector('.second-type');
        if (secondType) {
            secondType.style.display = 'none';
        }
    });
});

// 阻止下拉框内部点击事件冒泡，避免触发页面点击事件
document.querySelectorAll('.second-type').forEach(secondType => {
    secondType.addEventListener('click', function(e) {
        e.stopPropagation();
    });
});